<?php
class User extends CI_Controller {
    
    // 构造函数
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url','tools_helper'));
        $this->load->library('form_validation');
        $this->load->model('UserModel');
        // $this->output->enable_profiler(TRUE);
    }

    // index方法是默认方法
    public function index()
    {
        $this->load->view('signin/index.html');
    }

    // 登录
    public function check()
    {
        // 设置表单检验规则
        $this->form_validation->set_rules('email', '邮箱', 'required|trim|valid_email');
        $this->form_validation->set_rules('password', '密码', 'required|min_length[6]');
        // 运行表单检验
        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('signin/index.html');
        } else {
            // 读取数据库，检查用户名和密码是否一致
            $data = array (
                'email' => $this->input->post('email'),
                'password' => md5($this->input->post('password')),
                );
            if($this->UserModel->check($data)) {
                // 设置session
                $sessionData = array('uemail' => $this->input->post( 'email' ),);
                // 将用户名写入session
                $this->session->set_userdata( $sessionData );
                message( '/admin/index/', '登录成功！' );     
            } else {
                message( '/user/index', '信息不正确，请重新登录' );
            }            
        }        
    }

    // 显示注册页面
    public function regview()
    {
        $this->load->view('signin/reg.html');
    }
    // 注册用户
    public function reg()
    {
        
        // 设置验证规则
        $this->form_validation->set_rules('email', '邮箱', 'required|trim|is_unique[user.email]');
        $this->form_validation->set_rules('password', '密码', 'required|min_length[6]');
        $this->form_validation->set_rules('password2', '重复密码', 'callback_password_check');

        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('signin/reg.html');
        }
        else
        {
            // 将用户信息添加到数据库
            $data = array (
                'email' => $_POST['email'],
                'password' => md5($_POST['password']),
            );
            $this->UserModel->add($data);
            message('user/index','注册成功！');
        }
    }
    // 注销
    public function logout()
    {
        session_destroy();
        redirect('user/index');
    }
    // 重复密码检验
    public function password_check()
    {
        if ($_POST['password'] !== $_POST['password2'])
        {
            $this->form_validation->set_message('password_check', '两个密码不一致！');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
}